package com.kuang.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kuang.pojo.User;
import com.kuang.utils.JsonUtils;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@RestController //被这个注解标注的controller类下面的方法都不会走视图解析器 都会直接返回字符串
@Controller
public class UserController {

    @RequestMapping("/j1")
    @ResponseBody //被这个注解标注的controller方法不会走视图解析器，会直接返回一个字符串
    public String json1(){
        //jackson中 有个对象ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("小明",3,"男");

        String str = null;
        try {
           str = mapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return str;
    }

    @RequestMapping("/j2")
    @ResponseBody //被这个注解标注的controller方法不会走视图解析器，会直接返回一个字符串
    public String json2(){


        //创建一个对象
        User user = new User("小明",3,"男");
        User user1 = new User("小明1",3,"男");
        User user2 = new User("小明2",3,"男");
        User user3 = new User("小明3",3,"男");

        List<User> list = new ArrayList<>();
        list.add(user);
        list.add(user1);
        list.add(user2);
        list.add(user3);


        return JsonUtils.getJson(list);
    }

    @RequestMapping("/j3")
    @ResponseBody //被这个注解标注的controller方法不会走视图解析器，会直接返回一个字符串
    public String json3() throws JsonProcessingException {
        Date date = new Date();
        return JsonUtils.getJson(date);
    }

    @RequestMapping("/j4")
    @ResponseBody //被这个注解标注的controller方法不会走视图解析器，会直接返回一个字符串
    public String json4() throws JsonProcessingException {
        //创建一个对象
        User user = new User("小明",3,"男");
        User user1 = new User("小明1",3,"男");
        User user2 = new User("小明2",3,"男");
        User user3 = new User("小明3",3,"男");

        List<User> list = new ArrayList<>();
        list.add(user);
        list.add(user1);
        list.add(user2);
        list.add(user3);

       return JSON.toJSONString(list);
    }
}
